<script setup>

import {ajax, loadComponent,getToken,uuid,useEvent} from 'framework'
import {ref, defineAsyncComponent,watch,onMounted,nextTick,reactive,onBeforeUnmount} from 'vue'
import {useStore} from "store";
import {useRoute, useRouter} from 'vue-router'
import {message} from 'heyui'
import {useI18n} from "i18n";
const {t}=useI18n({
  zh:{
    "Home":"首页",
    "Modify Password":"修改密码",
    "Logout":"退出登录",
    "Old Password":"旧密码",
    "New Password":"新密码",
    "Repeat New Password":"重复新密码",
    "Entered Passwords Differ!":"两次输入的密码不一致!",
    "Bind WeChat":"微信绑定",
  }
})
const route = useRoute()

const router = useRouter()

const store = useStore()

const topbar = store.configs['PlatformConfig.TopBar']
const TopBar = defineAsyncComponent(() => loadComponent(topbar))
const title = document.title || 'Easy Admin'
const siderCollapsed = ref(localStorage.siderCollapsed == "true")
const breadcrumb = ref([{key: 'home', title: t('Home')}])

const switchSider=()=>{
  siderCollapsed.value=!siderCollapsed.value
  localStorage.siderCollapsed = siderCollapsed.value
}

const showMinMenu = ref(false)
const showLeftMenu = ref(true)

const leftMenu = ref([])

//菜单引用
const topMenuRef=ref()
const leftMenuRef=ref()
const popMenuRef=ref()

const openMenuCache = {}
let currentTopMenu = null
let currentLeft = null
let currentSelect = null

let userMenu = [
  {key: 'pwd', title: t('Modify Password'), icon: 'h-icon-lock'},
  {key: 'logout', title: t('Logout'), icon: 'h-icon-outbox'},
]
if (window._configs["LoginConfig.LOGIN_WX"] !== 'false'){
  userMenu = [
    {key: 'pwd', title: t('Modify Password'), icon: 'h-icon-lock'},
    {key:'wx',title: t('Bind WeChat'),icon:'h-icon-link'},
    {key: 'logout', title: t('Logout'), icon: 'h-icon-outbox'},
  ]
}
const pwdForm = ref(null),
    pwds = reactive({
      OldPassword: "",
      Password: "",
      ConfirmPassword: ""
    }),
    changePwd = ref(false);
const pwdRules = {
  rules: {
    Password: {
      maxLen: 18,
      minLen: 5
    }
  },
  combineRules: [{
    refs: ['Password', 'ConfirmPassword'],
    valid(a, b) {
      if (a != b) {
        return t('Entered Passwords Differ!');
      }
      return true;
    }
  }]
}
const dg1 = ref({})
function userMenuClick(data) {
  if (data == "logout") {
    ajax.get('system/logout').then((r) => {
      sessionStorage.clear()
      //localStorage.clear()
      //移除记住我的登录信息
      localStorage.removeItem('rmb_tk')
      let logoutEvent=new CustomEvent("logout",{
        bubbles: true, // 允许事件冒泡
        cancelable: true // 允许事件被取消
      })
      dispatchEvent(logoutEvent)
      location.hash = "/login"

      setTimeout(() => location.reload(), 1)
    })
  } else if (data == "pwd") {
    Object.assign(pwds, {
      OldPassword: "",
      Password: "",
      ConfirmPassword: ""
    })
    changePwd.value = true
  } else if (data == 'wx'){
    dg1.value.open()
  }
}
function updatePwd() {
  let validResult = pwdForm.value.valid();
  if (validResult.result) {
    if (pwds.Password != pwds.ConfirmPassword) {
      message(t('Entered Passwords Differ!'));
      return
    }
    //  console.log(toRaw(pwds))
    ajax.formPost("system/changePassword", pwds).then(r => {
      if (r.data.uk){
        sessionStorage.uk=r.data.uk
      }
      message(r.message||r.data.message)
      changePwd.value = false
    })
  }
}

function topMenuSelect(m) {
  if (currentTopMenu == m.key) {
    return
  }

  if (route.name == m.key) {
    return
  }
  if (m.path.startsWith("_blank:")) {
    open(m.path.substr(7), '_blank')
    let dt = findPathInMenu(store.user.menu, route.name)
    if(dt.length>0) {
      topMenuRef.value.select(dt[0].key)
    }
    return;
  }
  currentTopMenu = m.key
  if (m.path) {
    showLeftMenu.value = false

    router.push({name: m.key})
  } else {
    showLeftMenu.value = true

    leftMenu.value = m.children
    //选择默认
    if(openMenuCache[m.key]){
     // leftMenuRef.value.select(openMenuCache[m.key])
      //
      router.push({name: openMenuCache[m.key]})
    }else{
      let temp=m
      //查找第一个
      while(temp.children&&temp.children.length>0){
        temp=temp.children[0]
      }
      openMenuCache[m.key]=temp.key
      router.push({name: temp.key})
      //leftMenuRef.value.select(temp.key)
    }
  }

}

function leftMenuSelect(m) {
  if (currentLeft == m.key) {
    return
  }

  //openMenuCache
  if (route.name != m.key) {
    if (m.path.startsWith("_blank:")) {
        open(m.path.substr(7),'_blank')
       leftMenuRef.value.select(route.name)
      return;
    } else {
      //tempSelect=m.name
      openMenuCache[m.parent] = m.key
      location.hash=m.key
      //router.push({path: m.key})
    }
  }
  currentLeft = m.key
}
//首页弹出菜单选择
function menuSelect(m) {
  if (route.name != m.key) {
    if (m.path.startsWith("_blank:")) {
       open(m.path.substr(7),'_blank')
       popMenuRef.value.select(route.name)
       return
      // menu.value.select(tempSelect)
    } else {
      //tempSelect=m.name
      router.push({name: m.key})
    }
  }
}
function findPathInMenu(data, name) {
  for (let it of data) {
    if (it.key == name) {
      return [it]
    }
    if (it.children) {
      let ret = findPathInMenu(it.children, name)
      if (ret.length > 0) {
        return [it, ...ret]
      }
    }
  }
  return []
}
const initSelectMenu=(key)=>{
  // console.log(key)
  // console.log(route)
  let name = route.name;
  if (name) {
   // tempSelect=name
   // menu.value.select(name);
    let dt = findPathInMenu(store.user.menu, name)
    //breadcrumb.value = dt;
    if(dt.length>0){
      topMenuRef.value.select(dt[0].key)
      currentTopMenu=dt[0].key
      if(dt.length>1){
        showLeftMenu.value = true
        leftMenu.value=dt[0].children
        currentLeft = name
        nextTick(()=>{
          leftMenuRef.value.select(name)
        })
        showLeftMenu.value = true
      }else{
        showLeftMenu.value = false
      }
      breadcrumb.value=dt.map(it=>({title:it.title}))
    }else{
      showLeftMenu.value = false
    }

  } else {
    //breadcrumb.value = []
  }
}
watch(()=>route.name,initSelectMenu)
const eventBus=useEvent('server')
eventBus.addEventListener("notification",function (e){
  message("通知："+e.data,0)
})
let eventUuid=sessionStorage.euid||uuid()
sessionStorage.euid=eventUuid

let eventSource=null
function connectEventSource(){
  eventSource=new EventSource(`system/events?uid=${eventUuid}&_token=${getToken()}`)
  eventSource.onmessage = function(event) {
    //console.log('Received message: ' + event.data);
    if (event.data =="P"){
      return;
    }
    // let event=new Event("severEvent")
    let e = JSON.parse(event.data);
    eventBus.dispatchEvent(e.event,e.data)
  }
  eventSource.onerror=function (e){
   // console.log("es error",e)
    eventSource.close()
    setTimeout(connectEventSource,1000)
    //    .toFixed. connectEventSource()
  }
}
connectEventSource()

onMounted(()=>{
  initSelectMenu(route.name)
})
onBeforeUnmount(()=>{
  if (eventSource)
    eventSource.close()
})
function onPopMenuOpen(){
  popMenuRef.value.select(route.name)
}
</script>
<template>
  <Layout class="app-frame">
    <div class="top-menu">
      <div class="app-logo" style="height: 44px;overflow: hidden;">
        <router-link to="/" style="text-decoration: none">
          <div style="display: flex;align-items: center; height: 44px; min-width: 200px;">
          <span class="app-logo-icon"
                style="background: url(img/logo.png);margin-left:8px; width:30px;height:30px; background-size: 100% 100%;display: inline-block;
    margin-right: 10px;"></span>
            <span class="app-logo-text">{{ title }}</span>
          </div>
        </router-link>
      </div>
      <div style="flex: 1;white-space: nowrap;">
        <Menu className="main-hide"
              :datas="store.user.menu"
              :option="{childrenName:'subNode'}"
              mode="horizontal"
              @select="topMenuSelect"
              ref='topMenuRef'></Menu>
      </div>
      <component v-if="topbar" :is="TopBar"></component>
      <div style="height: 100%">
        <DropdownMenu className="app-header-dropdown"
                      trigger="hover" offset="0,0" :width="170" style="height: 100%"
                      placement="bottom-end" :datas="userMenu" @clickItem="userMenuClick">
          <span>{{ store.user.name }}({{ store.user.username }})</span>
        </DropdownMenu>
      </div>


    </div>
    <Layout :siderCollapsed="siderCollapsed">
      <Sider theme="dark"
             v-show="showLeftMenu"
             class="main-hide left-side-menu"
             style="">
        <Menu :datas="leftMenu"
              :mode="siderCollapsed?'collapse':'vertical'"
              ref='leftMenuRef'
              @select="leftMenuSelect"
              className="h-menu-dark layout-left-menu"
              style="background-color: #001529" accordion></Menu>
      </Sider>
      <Layout>
        <div class="breadcrumb-bar">
          <i :class="siderCollapsed ? 'icon-align-right':'icon-align-left'"
             class="main-hide"
             v-if="showLeftMenu"
             style="font-size: 20px;padding:5px 10px;user-select: none;cursor: pointer;color:rgba(0,0,0,.65)"
             @click="switchSider"/>
          <i class="icon-menu top-min-menu-button"
             @click="showMinMenu=true"
             style="font-size: 20px;padding:5px 10px;user-select: none;cursor: pointer;color:rgba(0,0,0,.65)"
          />
          <Breadcrumb :datas="breadcrumb" style="padding: 3px 3px 3px 10px;"></Breadcrumb>
        </div>
        <Content style="height: 100%;overflow: hidden;padding:0;">
          <RouterView v-slot="{ Component }">
            <transition name="fade">
<!--              <keep-alive>-->
                <component :is="Component"/>
<!--              </keep-alive>-->
            </transition>
          </RouterView>
        </Content>
      </Layout>
    </Layout>
    <Modal v-model="showMinMenu"
           type="drawer-left"
           @open="onPopMenuOpen"
           className="top-right-popup-menu" transparent>
      <div style="height: 100%;display: flex;flex-direction: column;">
        <div style="background: transparent;height: 45px;text-align: right">
        </div>
        <div style="background-color: rgb(0, 21, 41);height: 100%">
          <Menu :datas="store.user.menu"
                mode="vertical"
                @select="menuSelect"
                className="h-menu-dark"
                ref="popMenuRef"
                style="background-color: #001529;width: 200px" accordion></Menu>
        </div>
      </div>
    </Modal>
    <Modal v-model="changePwd" middle hasDivider>
      <template #header>{{t('Modify Password')}}</template>
      <div style="width:400px">
        <Form
            :labelWidth="170"
            ref="pwdForm"
            :rules="pwdRules"
            :model="pwds"
            class="title-suffix"
        >
          <FormItem :label="t('Old Password')" prop="OldPassword" required>
            <Input type="password" v-model="pwds.OldPassword"/>
          </FormItem>
          <FormItem :label="t('New Password')" prop="Password" required>
            <Input type="password" v-model="pwds.Password"/>
          </FormItem>
          <FormItem :label="t('Repeat New Password')" prop="ConfirmPassword" required>
            <Input type="password" v-model="pwds.ConfirmPassword"/>
          </FormItem>
        </Form>
      </div>
      <template #footer class="text-right">
        <Button @click="updatePwd">{{t('Confirm')}}</Button>
      </template>
    </Modal>
    <Dialog href="bindWxDialog.vue" ref="dg1" hasDivider hasCloseIcon>
      <template #header>{{t('Bind WeChat')}}</template>
      <template #footer="dg1">
        <Button @click="dg1.cancel">{{t('Cancel')}}</Button>
      </template>
    </Dialog>
  </Layout>
</template>
<style>
.layout-left-menu{
  overflow-y: auto;

}
.layout-left-menu::-webkit-scrollbar{
  width: 0;
}
.top-menu {
  //background-color: #2E73FF;
  //background-color: rgb(39,50,69) ;
  background-color: #0B3C5D;
  color: white;
  height: 45px;
  display: flex;
  align-items: center;
}

.top-menu .h-menu {
  background-color: transparent;
  color: #FFFFFF;
}

.top-menu .h-menu-mode-horizontal .h-menu-li .h-menu-show.h-menu-li-selected {
  background-color: rgba(0, 0, 0, .16);
  font-weight: bold;
}

.breadcrumb-bar {
  display: flex;
  align-items: center;
  color: #B2B2B2;
  box-shadow: 2px 1px 4px 0 rgba(0, 21, 41, 0.08);
  z-index: 3;
  height: 30px;
}

.app-header-dropdown.h-dropdowncustom-show > .h-icon-down {
  color: white;
}

.app-header-dropdown {
  height: 44px;
  display: flex;
  align-items: center;
}

.top-min-menu-button {
  display: none;
}

/**头部菜单**/
@media (max-width: 900px) {
  .h-layout.h-layout-sider-collapsed > .h-layout-sider {
    max-width: 0px;
    min-width: 0px;
  }

  .main-hide {
    display: none !important;
  }

  .top-min-menu-button {
    display: block;
  }
}

.top-right-popup-menu .h-notify-content {
  border-radius: 0;
}

.h-modal.top-right-popup-menu .h-notify-body {
  padding: 0;
}
.left-side-menu{
  background-color: #001529;
  display: flex;
  flex-direction: column;
  padding-top:10px
}
.app-logo-text{
  color: white;
  font-size: 16px;
  font-weight: 600;
  flex:1;
  padding-right: 10px;
}
</style>
